/*
 *	uvc_video.c  --  USB Video Class Gadget driver
 *
 *	Copyright (C) 2009-2010
 *	    Laurent Pinchart (laurent.pinchart@ideasonboard.com)
 *
 *	This program is free software; you can redistribute it and/or modify
 *	it under the terms of the GNU General Public License as published by
 *	the Free Software Foundation; either version 2 of the License, or
 *	(at your option) any later version.
 */

#include <linux/kernel.h>
#include <linux/device.h>
#include <linux/errno.h>
#include <linux/usb/ch9.h>
#include <linux/usb/gadget.h>
#include <linux/usb/video.h>

#include <media/v4l2-dev.h>

#include "uvc.h"
#include "uvc_queue.h"
#include "uvc_video.h"

/* --------------------------------------------------------------------------
 * Video codecs
 */
#define UVC_HEADER_LEN  (12)

#define UVC_RAM_BUF_USE_SIZE  (3072)
#define UVC_HELLO_FACE_HEADER_LEN  (16)
unsigned long long fh_get_pts64(void);
static int uvc_cmp_flag;
static int
uvc_video_encode_header(struct uvc_video *video, struct uvc_buffer *buf,
		u8 *data, int len)
{
	unsigned int uvc_header_len = 0;

#ifdef CONFIG_UVC_WINDOWS_HELLO_FACE
	if (video->stream_id == 0)
		uvc_header_len = UVC_HEADER_LEN;
	else
		uvc_header_len = UVC_HEADER_LEN/*  + UVC_HELLO_FACE_HEADER_LEN */;
	if (video->stream_id == 1 && uvc_cmp_flag == 0)
		uvc_header_len = UVC_HEADER_LEN + UVC_HELLO_FACE_HEADER_LEN;
#else
	uvc_header_len = UVC_HEADER_LEN;
#endif
	memset(data, 0, uvc_header_len);
	data[0] = uvc_header_len;
	data[1] = UVC_STREAM_EOH | video->fid;
	if (buf->bytesused - video->queue.buf_used <= len - uvc_header_len)
	{
		data[1] |= UVC_STREAM_EOF/*  | UVC_STREAM_RES */;
	}
	if (/* buf->buf.vb2_buf.timestamp &&  */uvc_header_len >= 12)
	{
		u64 fream_timestamp = video->timestamp;
		u64 clock_timestamp = fh_get_pts64() * 1000;

		if (video->still_image_flag) {
			data[1] |= UVC_STREAM_EOH | 0;
			data[1] |= UVC_STREAM_STI;
		}
		data[1] |= UVC_STREAM_PTS;
		data[1] |= UVC_STREAM_SCR;
		data[2] = (u8)(fream_timestamp & 0xff);
		data[3] = (u8)(fream_timestamp >> 8 & 0xff);
		data[4] = (u8)(fream_timestamp >> 16 & 0xff);
		data[5] = (u8)(fream_timestamp >> 24 & 0xff);

		data[6] = (u8)(clock_timestamp & 0xff);
		data[7] = (u8)(clock_timestamp >> 8 & 0xff);
		data[8] = (u8)(clock_timestamp >> 16 & 0xff);
		data[9] = (u8)(clock_timestamp >> 24 & 0xff);
		data[10] = 0;
		data[11] = 0;
	}
#ifdef CONFIG_UVC_WINDOWS_HELLO_FACE
		if (uvc_header_len == (UVC_HEADER_LEN + UVC_HELLO_FACE_HEADER_LEN))
		{
			memset(&data[UVC_HEADER_LEN], 0, UVC_HELLO_FACE_HEADER_LEN);
			data[UVC_HEADER_LEN] = 0x06;
			data[UVC_HEADER_LEN + 4] = 0x10;
			if (video->fid)
				data[UVC_HEADER_LEN + 8] = 0x01;

		}
#endif
	if (video->stream_id == 1)
		uvc_cmp_flag++;
	return uvc_header_len;
}

static int uvc_video_send_header(struct usb_ep *ep, struct usb_request *req)
{
	unsigned char *bufreq = (unsigned char *)req->buf;
	struct uvc_video *video = req->context;
	int ret = 0;
	unsigned int uvc_header_len = 0;

#ifdef CONFIG_UVC_WINDOWS_HELLO_FACE
	if (video->stream_id == 0)
		uvc_header_len = UVC_HEADER_LEN;
	else
		uvc_header_len = UVC_HEADER_LEN/*  + UVC_HELLO_FACE_HEADER_LEN */;
	if (video->stream_id == 1 && uvc_cmp_flag == 0)
		uvc_header_len = UVC_HEADER_LEN + UVC_HELLO_FACE_HEADER_LEN;
#else
	uvc_header_len = UVC_HEADER_LEN;
#endif
	bufreq[0] = uvc_header_len;
	bufreq[1] = UVC_STREAM_EOH | video->fid;

	if (/* video->timestamp &&  */uvc_header_len >= 12) {
		u64 fream_timestamp = video->timestamp;
		u64 clock_timestamp = fh_get_pts64() * 1000;

		bufreq[1] |= UVC_STREAM_PTS;
		bufreq[1] |= UVC_STREAM_SCR;
		bufreq[2] = (u8)(fream_timestamp & 0xff);
		bufreq[3] = (u8)(fream_timestamp >> 8 & 0xff);
		bufreq[4] = (u8)(fream_timestamp >> 16 & 0xff);
		bufreq[5] = (u8)(fream_timestamp >> 24 & 0xff);

		bufreq[6] = (u8)(clock_timestamp & 0xff);
		bufreq[7] = (u8)(clock_timestamp >> 8 & 0xff);
		bufreq[8] = (u8)(clock_timestamp >> 16 & 0xff);
		bufreq[9] = (u8)(clock_timestamp >> 24 & 0xff);
		bufreq[10] = 0;
		bufreq[11] = 0;
		if (video->still_image_flag) {
			bufreq[1] |= UVC_STREAM_EOH | 0;
			bufreq[1] |= UVC_STREAM_STI;
		}
	}
#ifdef CONFIG_UVC_WINDOWS_HELLO_FACE
		if (uvc_header_len == (UVC_HEADER_LEN + UVC_HELLO_FACE_HEADER_LEN))
		{
			memset(&bufreq[UVC_HEADER_LEN], 0, UVC_HELLO_FACE_HEADER_LEN);
			bufreq[UVC_HEADER_LEN] = 0x06;
			bufreq[UVC_HEADER_LEN + 4] = 0x10;
			if (video->fid)
				bufreq[UVC_HEADER_LEN + 8] = 0x01;
	}
#endif
	req->length = uvc_header_len;

	if ((ret = usb_ep_queue(ep, req, GFP_ATOMIC)) < 0) {
		printk(KERN_INFO "Failed to queue request (%d).\n", ret);
		usb_ep_set_halt(ep);
		return ret;
	}
	if (video->stream_id == 1)
		uvc_cmp_flag++;
	return 0;
}

static int
uvc_video_encode_data(struct uvc_video *video, struct uvc_buffer *buf,
		u8 *data, int len)
{
	struct uvc_video_queue *queue = &video->queue;
	unsigned int nbytes;
	void *mem;

	/* Copy video data to the USB buffer. */
	mem = buf->mem + queue->buf_used;
	nbytes = min((unsigned int)len, buf->bytesused - queue->buf_used);

	memcpy(data, mem, nbytes);
	queue->buf_used += nbytes;

	return nbytes;
}

static void
uvc_video_encode_bulk(struct usb_request *req, struct uvc_video *video,
		struct uvc_buffer *buf)
{
	void *mem = req->buf;
	int len = video->req_size;
	int ret;

	if (video->queue.buf_used == 0 && buf->buf.vb2_buf.timestamp){
		video->timestamp = buf->buf.vb2_buf.timestamp;
		if (video->timestamp/1000 == UVC_STILL_IMAGE_MAGIC_FLAG)
			video->still_image_flag = 1;
	}
	/* Add a header at the beginning of the payload. */
	if (video->payload_size == 0) {
		ret = uvc_video_encode_header(video, buf, mem, len);
		video->payload_size += ret;
		mem += ret;
		len -= ret;
	}

	/* Process video data. */
	len = min((int)(video->max_payload_size - video->payload_size), len);
	ret = uvc_video_encode_data(video, buf, mem, len);

	video->payload_size += ret;
	len -= ret;

	req->length = video->req_size - len;
	req->zero = video->payload_size == video->max_payload_size;

	if (buf->bytesused == video->queue.buf_used) {
		video->queue.buf_used = 0;
		if (video->stream_id == 1)
			uvc_cmp_flag = 0;
		buf->state = UVC_BUF_STATE_DONE;
		uvcg_queue_next_buffer(&video->queue, buf);
		video->fid ^= UVC_STREAM_FID;
		if (video->still_image_flag)
			video->still_image_flag = 0;
		video->payload_size = 0;
	}

	if (video->payload_size == video->max_payload_size ||
	    buf->bytesused == video->queue.buf_used)
		video->payload_size = 0;
}

static void
uvc_video_encode_isoc(struct usb_request *req, struct uvc_video *video,
		struct uvc_buffer *buf)
{
	void *mem = req->buf;
	int len = video->req_size;
	int ret;


	if (video->queue.buf_used == 0 && buf->buf.vb2_buf.timestamp){
		video->timestamp = buf->buf.vb2_buf.timestamp;
		if (video->timestamp/1000 == UVC_STILL_IMAGE_MAGIC_FLAG)
			video->still_image_flag = 1;
	}
	/* Add the header. */
	ret = uvc_video_encode_header(video, buf, mem, len);
	mem += ret;
	len -= ret;

	/* Process video data. */
	ret = uvc_video_encode_data(video, buf, mem, len);
	len -= ret;

	req->length = video->req_size - len;

	if (buf->bytesused == video->queue.buf_used) {
		if (video->stream_id == 1)
			uvc_cmp_flag = 0;
		video->queue.buf_used = 0;
		buf->state = UVC_BUF_STATE_DONE;
		uvcg_queue_next_buffer(&video->queue, buf);
		video->fid ^= UVC_STREAM_FID;
		if (video->still_image_flag)
			video->still_image_flag = 0;
	}
}

/* --------------------------------------------------------------------------
 * Request handling
 */

/*
 * I somehow feel that synchronisation won't be easy to achieve here. We have
 * three events that control USB requests submission:
 *
 * - USB request completion: the completion handler will resubmit the request
 *   if a video buffer is available.
 *
 * - USB interface setting selection: in response to a SET_INTERFACE request,
 *   the handler will start streaming if a video buffer is available and if
 *   video is not currently streaming.
 *
 * - V4L2 buffer queueing: the driver will start streaming if video is not
 *   currently streaming.
 *
 * Race conditions between those 3 events might lead to deadlocks or other
 * nasty side effects.
 *
 * The "video currently streaming" condition can't be detected by the irqqueue
 * being empty, as a request can still be in flight. A separate "queue paused"
 * flag is thus needed.
 *
 * The paused flag will be set when we try to retrieve the irqqueue head if the
 * queue is empty, and cleared when we queue a buffer.
 *
 * The USB request completion handler will get the buffer at the irqqueue head
 * under protection of the queue spinlock. If the queue is empty, the streaming
 * paused flag will be set. Right after releasing the spinlock a userspace
 * application can queue a buffer. The flag will then cleared, and the ioctl
 * handler will restart the video stream.
 */
static void
uvc_video_complete(struct usb_ep *ep, struct usb_request *req)
{
	struct uvc_video *video = req->context;
	struct uvc_video_queue *queue = &video->queue;
	struct uvc_buffer *buf;
	unsigned long flags;
	int ret;
	struct uvc_device *uvc = video_to_uvc(video);

	if (video_to_bulk_flag(video) && uvc->bulk_stream_off)
		return;

	switch (req->status) {
	case 0:
		break;

	case -ESHUTDOWN:	/* disconnect from host. */
		printk(KERN_DEBUG "VS request cancelled.\n");
		uvcg_queue_cancel(queue, 1);
		goto requeue;
	case -EXDEV:
		printk(KERN_INFO "VS request completed with status %d\n",
			req->status);
		if (video->still_image_flag)
			goto requeue;
		uvcg_queue_cancel(queue, 0);
		goto requeue;
	case -ECONNRESET:
		printk(KERN_INFO "VS request completed with status %d\n",
			req->status);
		uvcg_queue_cancel(queue, 1);
		goto requeue;
	default:
		printk(KERN_INFO "VS request completed with status %d\n",
			req->status);
		uvcg_queue_cancel(queue, 0);
		goto requeue;
	}

	spin_lock_irqsave(&video->queue.irqlock, flags);
	buf = uvcg_queue_head(&video->queue);
	if (buf == NULL) {
		if (video_to_bulk_flag(video)) {
			spin_unlock_irqrestore(&video->queue.irqlock, flags);
			goto requeue;
		} else {
			ret = uvc_video_send_header(ep, req);
			spin_unlock_irqrestore(&video->queue.irqlock, flags);
			if (ret < 0)
				goto requeue;
			else
				return;
		}
	}

	video->encode(req, video, buf);

	if ((ret = usb_ep_queue(ep, req, GFP_ATOMIC)) < 0) {
		printk(KERN_INFO "Failed to queue request (%d).\n", ret);
		usb_ep_set_halt(ep);
		spin_unlock_irqrestore(&video->queue.irqlock, flags);
		uvcg_queue_cancel(queue, 0);
		goto requeue;
	}
	spin_unlock_irqrestore(&video->queue.irqlock, flags);

	return;

requeue:
	spin_lock_irqsave(&video->req_lock, flags);
	list_add_tail(&req->list, &video->req_free);
	spin_unlock_irqrestore(&video->req_lock, flags);
}

static int
uvc_video_free_requests(struct uvc_video *video)
{
	unsigned int i;

	for (i = 0; i < UVC_NUM_REQUESTS; ++i) {
		if (video->req[i]) {
			video->req[i]->buf = NULL;
			usb_ep_free_request(video->ep, video->req[i]);
			video->req[i] = NULL;
		}

		if (video->req_buffer[i]) {
			if (video->ram_buf_addr == NULL)
				kfree(video->req_buffer[i]);

			video->req_buffer[i] = NULL;
		}
	}
	if (video->ram_buf_addr) {
		iounmap(video->ram_buf_addr);
		video->ram_buf_addr = NULL;
	}

	INIT_LIST_HEAD(&video->req_free);
	video->req_size = 0;
	return 0;
}

static int
uvc_video_alloc_requests(struct uvc_video *video)
{
	unsigned int req_size;
	unsigned int i;
	int ret = -ENOMEM;

	BUG_ON(video->req_size);

	if (video_to_bulk_flag(video))
		req_size = video->max_payload_size;
	else {
		req_size = video->ep->maxpacket
			* max_t(unsigned int, video->ep->maxburst, 1)
			* (video->ep->mult);

#if defined(CONFIG_UVC_USB_RAM_BUF) && defined(CONFIG_USB_DWC3)
		if (video->ram_buf_addr ==NULL &&
			req_size > UVC_RAM_BUF_USE_SIZE &&
			req_size * UVC_NUM_REQUESTS <= 1024 * 540 && video->stream_id == 0)/* RAM buf size */
		{
			video->ram_buf_addr = ioremap(CONFIG_PHY_RAM_BUF_ADDR, req_size * UVC_NUM_REQUESTS);
			memset(video->ram_buf_addr, 0, req_size * UVC_NUM_REQUESTS);
		} else if (req_size * UVC_NUM_REQUESTS > 1024 * 540)
			pr_err("[Warning]: UVC_NUM_REQUESTS %d * req_size %d > RAM_BUF_SIZE %d\n",
				UVC_NUM_REQUESTS, req_size, 1024 * 540);
#endif
	}

	pr_err("video->ep->maxburst %d maxpacket %d video->ep->mult %d ram_buf_addr %p\n",
		video->ep->maxburst, video->ep->maxpacket, video->ep->mult, video->ram_buf_addr);
	for (i = 0; i < UVC_NUM_REQUESTS; ++i) {
		if (video->ram_buf_addr) {
			video->req_buffer[i] = video->ram_buf_addr + (i * req_size);
		} else {
			video->req_buffer[i] = kmalloc(req_size, GFP_KERNEL);
		}
		if (video->req_buffer[i] == NULL)
			goto error;

		video->req[i] = usb_ep_alloc_request(video->ep, GFP_KERNEL);
		if (video->req[i] == NULL)
			goto error;

		video->req[i]->buf = video->req_buffer[i];
#if defined(CONFIG_UVC_USB_RAM_BUF) && defined(CONFIG_USB_DWC3)
		if (video->ram_buf_addr)
			video->req[i]->dma = CONFIG_PHY_RAM_BUF_ADDR + (i * req_size);
#endif
		video->req[i]->length = 0;
		video->req[i]->complete = uvc_video_complete;
		video->req[i]->context = video;

		list_add_tail(&video->req[i]->list, &video->req_free);
	}

	video->req_size = req_size;

	return 0;

error:
	uvc_video_free_requests(video);
	return ret;
}

/* --------------------------------------------------------------------------
 * Video streaming
 */

/*
 * uvcg_video_pump - Pump video data into the USB requests
 *
 * This function fills the available USB requests (listed in req_free) with
 * video data from the queued buffers.
 */
int uvcg_video_pump(struct uvc_video *video)
{
	struct uvc_video_queue *queue = &video->queue;
	struct usb_request *req;
	struct uvc_buffer *buf;
	unsigned long flags;
	struct uvc_device *uvc = video_to_uvc(video);

	int ret;

	/* FIXME TODO Race between uvcg_video_pump and requests completion
	 * handler ???
	 */

	while (1) {
		/* Retrieve the first available USB request, protected by the
		 * request lock.
		 */
		spin_lock_irqsave(&video->req_lock, flags);
		if (list_empty(&video->req_free)) {
			spin_unlock_irqrestore(&video->req_lock, flags);
			return 0;
		}
		req = list_first_entry(&video->req_free, struct usb_request,
					list);
		list_del(&req->list);
		spin_unlock_irqrestore(&video->req_lock, flags);

		/* Retrieve the first available video buffer and fill the
		 * request, protected by the video queue irqlock.
		 */
		spin_lock_irqsave(&queue->irqlock, flags);
		buf = uvcg_queue_head(queue);
		if (buf == NULL) {
			spin_unlock_irqrestore(&queue->irqlock, flags);
			break;
		}

		video->encode(req, video, buf);

		/* Queue the USB request */
		if (video_to_bulk_flag(video) && uvc->bulk_stream_off) {
			spin_unlock_irqrestore(&queue->irqlock, flags);
			uvcg_queue_cancel(queue, 0);
			return 0;
		}

		ret = usb_ep_queue(video->ep, req, GFP_ATOMIC);
		if (ret < 0) {
			printk(KERN_INFO "Failed to queue request (%d)\n", ret);
			usb_ep_set_halt(video->ep);
			spin_unlock_irqrestore(&queue->irqlock, flags);
			uvcg_queue_cancel(queue, 0);
			break;
		}
		spin_unlock_irqrestore(&queue->irqlock, flags);
	}

	spin_lock_irqsave(&video->req_lock, flags);
	list_add_tail(&req->list, &video->req_free);
	spin_unlock_irqrestore(&video->req_lock, flags);
	return 0;
}

/*
 * Enable or disable the video stream.
 */
int uvcg_video_enable(struct uvc_video *video, int enable)
{
	unsigned int i;
	int ret;

	if (video->ep == NULL) {
		printk(KERN_INFO "Video enable failed, device is "
			"uninitialized.\n");
		return -ENODEV;
	}

	if (!enable) {
		for (i = 0; i < UVC_NUM_REQUESTS; ++i)
			if (video->req[i])
				usb_ep_dequeue(video->ep, video->req[i]);

		uvc_video_free_requests(video);
		uvcg_queue_enable(&video->queue, 0);
		return 0;
	}

	if ((ret = uvcg_queue_enable(&video->queue, 1)) < 0)
		return ret;

	if ((ret = uvc_video_alloc_requests(video)) < 0)
		return ret;

	if (video->max_payload_size) {
		video->encode = uvc_video_encode_bulk;
		video->payload_size = 0;
	} else
		video->encode = uvc_video_encode_isoc;

	return uvcg_video_pump(video);
}

/*
 * Initialize the UVC video stream.
 */
int uvcg_video_init(struct uvc_video *video)
{
	INIT_LIST_HEAD(&video->req_free);
	spin_lock_init(&video->req_lock);

	video->fcc = V4L2_PIX_FMT_YUYV;
	video->bpp = 16;
	video->width = 3840;
	video->height = 2160;
	video->imagesize = 3840 * 2160 * 2;
	if (video_to_bulk_flag(video))
		video->max_payload_size = 1024 * CONFIG_UVC_EP_BULK_PACKET_NUM;
	/* Initialize the video buffers queue. */
	uvcg_queue_init(&video->queue, V4L2_BUF_TYPE_VIDEO_OUTPUT,
			&video->mutex);
	return 0;
}

